package com.nmf.site.biz.pay.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.nmf.site.biz.pay.ali.entity.AliNotifyParam;
import com.nmf.site.biz.pay.ali.rsa.RsaAlipayNotify;
import com.nmf.site.biz.pay.ali.service.AliSignVerService;
import com.nmf.site.biz.pay.ali.util.AlipayCore;
import com.nmf.site.biz.pay.ali.util.AlipayNotify;
import com.nmf.site.biz.pay.wechat.service.NotifyService;

/**
 * 送机
 */
@Controller
@RequestMapping("pay/ali")
public class AliNotifyController {
	private Logger log = LoggerFactory.getLogger(AliNotifyController.class);
	@Autowired
	NotifyService notifyService;

	@Autowired
	AlipayNotify alipayNotify;

	@Autowired
	AlipayCore alipayCore;

	@Autowired
	AliSignVerService aliSignVerService;

	@RequestMapping(value = "v1.0/p/notify", method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public String alipayNotify(@Valid AliNotifyParam param, BindingResult result, HttpServletRequest request) throws UnsupportedEncodingException {
		long time = System.currentTimeMillis();
		Set<String> keyset = request.getParameterMap().keySet();
		StringBuffer sbstr = new StringBuffer();
		log.info("v1.0/alipay/notify/pay 1:" + (System.currentTimeMillis() - time));
		time = System.currentTimeMillis();
		Map<String, String> pmap = new HashMap<String, String>();
		for (String key : keyset) {
			String[] values = request.getParameterValues(key);
			for (int i = 0; i < values.length; i++) {
				String value = values[i];
				pmap.put(key, value);
				sbstr.append(key + "=" + value + "&");
			}
		}
		log.info("v1.0/alipay/notify/pay 2:" + (System.currentTimeMillis() - time));
		time = System.currentTimeMillis();
		String jparam = JSON.toJSONString(param);
		log.info("aliwebpay notify is json is [" + jparam + "]");
		String signType = pmap.get("sign_type");
		boolean isSign = false;
		if ("MD5".equals(signType)) {
			isSign = alipayNotify.verify(pmap);
		} else {
			isSign = RsaAlipayNotify.verify(pmap);
		}
		log.info("v1.0/alipay/notify/pay 3:" + (System.currentTimeMillis() - time));
		time = System.currentTimeMillis();
		if (isSign) {
			notifyService.notifyAli(param.getTotal_fee(),param.getNotify_id(), param.getTrade_status(),param.getOut_trade_no(),param.getTrade_no(), jparam, sbstr.toString());
			return "SUCCESS";
		} else {
			return "FAILED";
		} 

	}


}
